<template>
    <div class="app-container">
        <el-row :gutter="20">
            <el-col :span="12">
                <el-card shadow="always" header="告警统计情况">
                    <el-table :data="alarmStatisticsData" style="width: 100%" height="40%">
                        <el-table-column fixed prop="month" label="月份" width="60" align="center" />
                        <el-table-column fixed prop="county" label="区县" width="120" align="center" />
                        <el-table-column prop="realTimeAlarm1DayNum" label="超过1天未恢复量" min-width="160" align="center"
                            sortable />
                        <!-- <el-table-column prop="realTimeAlarmRatio" label="未恢复量规模占比" width="160" align="center"
                            sortable /> -->
                        <el-table-column prop="realTimeAlarmRatio" label="超1天告警规模比例" width="160" align="center"
                            sortable />
                        <el-table-column prop="realTimeAlarmNum" label="未恢复总量" width="140" align="center" sortable />
                        <el-table-column prop="realTimeAlarm3DaysNum" label="超过3天未恢复量" min-width="160" align="center"
                            sortable />
                        <template #empty>
                            <el-empty :image-size="40" />
                        </template>
                    </el-table>
                </el-card>
            </el-col>
            <el-col :span="12">
                <el-card shadow="always" header="告警对比情况">
                    <!-- <el-card shadow="always" header="当月每日各区县的告警数量趋势"> -->
                    <div id='echart' style="width: 100%;height:440px"></div>
                </el-card>
            </el-col>
        </el-row>

        <el-row>
            <el-col :span="24">
                <el-card shadow="always" header="实时告警详情" style="margin-top: 20px;">
                    <el-form :model="queryParams" :inline="true" label-width="120px">
                        <el-form-item label="所属区县：" prop="county">
                            <el-select v-model="queryParams.county" placeholder="请选择所属区县" clearable
                                style="width: 240px">
                                <el-option v-for="dict in nhp_county_type" :key="dict.value" :label="dict.label"
                                    :value="dict.value" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="网元名称：" prop="neName">
                            <el-input v-model="queryParams.neName" placeholder="请输入网元名称" clearable
                                style="width: 240px" />
                        </el-form-item>
                        <el-form-item label="网络制式：" prop="networkType">
                            <el-select v-model="queryParams.networkType" placeholder="请选择网络制式" clearable
                                style="width: 240px">
                                <el-option v-for="item in networkTypeOptions" :key="item.value" :label="item.key"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                        <!-- <el-form-item label="告警工程状态：" prop="networkType">
                            <el-select v-model="queryParams.networkType" placeholder="请选择告警工程" style="width: 240px">
                                <el-option v-for="dict in nhp_network_type" :key="dict.value" :label="dict.label"
                                    :value="dict.value" />
                            </el-select>
                        </el-form-item> -->
                        <el-form-item label="告警标题：" prop="alarmTitle">
                            <el-input v-model="queryParams.alarmTitle" placeholder="请输入告警标题" clearable
                                style="width: 240px" />
                        </el-form-item>
                        <el-form-item label="首次发生时间：" prop="eventTime">
                            <el-date-picker v-model="queryParams.eventTime" type="daterange" start-placeholder="开始时间"
                                end-placeholder="结束时间" :size="size" />
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" icon="Search" @click="listRealTimeAlarmData">查询</el-button>
                            <el-button @click="unsetQueryForm"><el-icon>
                                    <RefreshRight />
                                </el-icon>重置</el-button>
                            <el-button type="primary" icon="Download" @click="exportData">导出</el-button>
                            <el-button type="primary" icon="Tools" @click="showConfigDialog">配置</el-button>
                        </el-form-item>

                    </el-form>
                    <el-table :data="realTimeAlarmData" style="width: 100%" @sort-change="sortChange" row-key="alarmId"
                        @filter-change="filterChange">
                        <el-table-column fixed prop="county" label="区县" width="150" align="center" />
                        <el-table-column prop="neName" label="网元名称" width="250" align="center" show-overflow-tooltip />
                        <el-table-column prop="alarmTitle" label="告警标题" width="250" align="center" />
                        <el-table-column prop="eventTime" label="告警首次发生时间" :formatter="dateFormatter" width="250"
                            align="center" />
                        <el-table-column prop="networkType" label="网络类型" width="150" align="center"
                            :formatter="networkTypeFormatter" />
                        <!-- <el-table-column prop="networkType1" label="告警工程状态" width="150" align="center" /> -->
                        <el-table-column prop="serious" label="是否影响业务" width="150" align="center"
                            filter-multiple="false" :filters="[
                                { text: '是', value: 1 },
                                { text: '否', value: 0 },
                            ]" :column-key="'serious'" filter-placement="bottom-end">
                            <template #default="scope">
                                <el-tag :type="scope.row.serious == 1 ? 'danger' : 'success'" disable-transitions>{{
                                    scope.row.serious
                                        == 1 ? "是" : "否" }}</el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column prop="equipmentManufacturerName" label="厂商" width="150" align="center" />
                        <el-table-column prop="impact" label="对业务的影响" width="150" align="center" />
                        <el-table-column prop="suggestion" label="处理建议" width="150" align="center" />
                        <el-table-column fixed="right" label="操作" align="center">
                            <template #default="scope">
                                <el-button link type="primary" size="small"
                                    @click="showDetailDialog(scope.row.alarmId)">详情</el-button>
                                <!-- <el-button size="large" link type="primary" circle icon="Aim"
                                    @click="aimPosition(scope.row)" /> -->
                            </template>
                        </el-table-column>
                    </el-table>
                    <!-- <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                        :page-sizes="[10, 50, 100, 200]" :small="small" :disabled="disabled" :background="background"
                        layout="total, sizes, prev, pager, next" :total="total" @size-change="listRealTimeAlarmData"
                        @current-change="listRealTimeAlarmData" /> -->
                    <pagination v-show="total > 0" :total="total" v-model:page="currentPage" v-model:limit="pageSize"
                        @pagination="listRealTimeAlarmData" :autoScroll="false" />
                </el-card>
            </el-col>
        </el-row>
        <el-dialog v-model="detailDialogVisible" title="查看告警详情" width="1000" @closed="closeDialog">
            <el-form :inline="true" :model="alarmForm" label-width="200px">
                <el-form-item label="告警ID">
                    <el-input v-model="alarmForm.alarmId" disabled style="width: 635px" />
                </el-form-item>
                <el-form-item label="告警标题">
                    <el-input v-model="alarmForm.alarmTitle" disabled style="width: 200px" />
                </el-form-item>
                <el-form-item label="所属地市">
                    <el-input v-model="alarmForm.city" disabled style="width: 200px" />
                </el-form-item>
                <el-form-item label="所属区县">
                    <el-input v-model="alarmForm.county" disabled style="width: 200px" />
                </el-form-item>
                <el-form-item label="首次发生时间">
                    <el-input v-model="alarmForm.eventTime" disabled style="width: 200px" />
                </el-form-item>
                <el-form-item label="厂商名称">
                    <el-input v-model="alarmForm.equipmentManufacturerName" disabled style="width: 200px" />
                </el-form-item>
                <el-form-item label="网络类型">
                    <el-input v-model="alarmForm.networkType" disabled style="width: 200px" />
                </el-form-item>

                <el-form-item label="告警定位信息">
                    <el-input type="textarea" v-model="alarmForm.locateInfo" disabled style="width: 635px" />
                </el-form-item>
                <el-form-item label="告警正文">
                    <el-input type="textarea" v-model="alarmForm.alarmText" disabled style="width: 635px" :rows="8" />
                </el-form-item>
            </el-form>
        </el-dialog>
        <el-dialog v-model="configDialogVisible" title="配置信息" width="1000" @closed="closeDialog">
            <el-tabs type="border-card">
                <el-tab-pane label="剔除告警列表">
                    <el-row>
                        <el-button type="primary" @click="showAddAlarmExclude">新增</el-button>
                    </el-row>
                    <el-table :data="alarmExcludeData" style="width: 100%">
                        <el-table-column fixed prop="id" label="ID" width="150" align="center" />
                        <el-table-column prop="alarmTopic" label="告警主题" align="center" />
                        <el-table-column fixed="right" label="操作" min-width="50" align="center">
                            <template #default="scope">
                                <el-button link type="primary" icon="Delete"
                                    @click="handleDelete(scope.row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
            </el-tabs>
        </el-dialog>
        <el-dialog v-model="addDialogVisible" title="新增剔除告警" width="600" @closed="closeAddDialog">
            <el-form :inline="true" :model="addForm" label-width="200px">
                <el-form-item label="告警标题">
                    <el-input v-model="addForm.alarmTopic" style="width: 200px" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="doAddAlarmExclude">
                        确定
                    </el-button>
                    <el-button @click="addDialogVisible = false">取消</el-button>
                </div>
            </template>
        </el-dialog>

        <export-dialog ref="refExportDialog" @directExport="directExportData" @submitApprove="submitApprove" />
    </div>
</template>

<script setup>

import { queryRealTimeAlarm, queryRealTimeAlarmByAlarmId, queryMaintenanceAlarmStatistics, queryAlarmExcludeList, addAlarmExclude, deleteAlarmExclude } from '@/api/biz/maintenance';
import * as echarts from 'echarts';

/* import mittBus from "@/utils/mittBus"; // mitt - 组件传参工具
mittBus.emit("setWaterMarker", 130); */

const { proxy } = getCurrentInstance();
const { nhp_county_type } = proxy.useDict("nhp_county_type");
import { useConfigStore } from '@/store/modules/config.js'
import { ElMessage } from 'element-plus'
import testJson from './data.json'


const queryParams = ref([])
const alarmStatisticsData = ref([])

const realTimeAlarmData = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const alarmForm = ref({})
const detailDialogVisible = ref(false)
const refExportDialog = ref(null)

const configStoreData = useConfigStore()
let securityFlagConfig = configStoreData.configList.filter(item => item.configKey === 'sys.securityFlag')[0]

const networkTypeOptions = [
    {
        key: "4G",
        value: "103"
    },
    {
        key: "5G",
        value: "108"
    },
    {
        key: "2G",
        value: "101"
    }
]
const nowStatus = ref();
const configDialogVisible = ref(false)
const alarmExcludeData = ref([])
const addDialogVisible = ref(false)
const addForm = ref({})

const aimPosition = (row) => {
    console.log('aimPosition', row)

    if (row.longitude && row.latitude) {
        /* refDetailDialog.value.hide();

        emit('setAutoPopup', row)

        setTimeout(() => {
            refDetailDialog.value.show();
        }, 3000) */

        return
    }

    proxy.$modal.msgWarning(`经纬度数据有误,无法跳转`);

    /* refDetailDialog.value.hide();

    emit('setAutoPopup', row)

    setTimeout(() => {
        refDetailDialog.value.show();
    }, 3000) */
}


function listRealTimeAlarmData() {
    const param = {}
    param.pageSize = pageSize.value;
    param.pageNum = currentPage.value;
    param.county = queryParams.value.county
    param.neName = queryParams.value.neName
    param.alarmTitle = queryParams.value.alarmTitle
    param.networkType = queryParams.value.networkType
    param.serious = nowStatus.value;
    if (queryParams.value.eventTime && queryParams.value.eventTime.length > 0) {
        param.start = queryParams.value.eventTime[0].toLocaleDateString()
        param.end = queryParams.value.eventTime[1].toLocaleDateString()
    }

    queryRealTimeAlarm(param).then(res => {
        total.value = res.total
        realTimeAlarmData.value = res.rows
    })
}

function dateFormatter(row, column, cellValue, index) {
    if (!cellValue) { return }
    // 创建一个新的 Date 对象
    var originalDate = new Date(cellValue);

    // 获取年、月、日、时、分、秒
    var year = originalDate.getFullYear();
    var month = ("0" + (originalDate.getMonth() + 1)).slice(-2);
    var day = ("0" + originalDate.getDate()).slice(-2);
    var hours = ("0" + originalDate.getHours()).slice(-2);
    var minutes = ("0" + originalDate.getMinutes()).slice(-2);
    var seconds = ("0" + originalDate.getSeconds()).slice(-2);

    // 格式化输出
    var formattedDateTimeString = year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
    return formattedDateTimeString;
}

function networkTypeFormatter(row, column, cellValue, index) {
    if (!cellValue) { return }
    if (cellValue == '103') {
        return '4G';
    } else if (cellValue == '108') {
        return '5G';
    } else if (cellValue == '101') {
        return '2G';
    }
}

function showDetailDialog(alarmId) {
    //获取告警信息
    let param = { alarmId: alarmId }
    queryRealTimeAlarmByAlarmId(param).then(res => {
        alarmForm.value = res.data
        alarmForm.value.eventTime = dateFormatter(null, null, alarmForm.value.eventTime, null)
        alarmForm.value.networkType = networkTypeFormatter(null, null, alarmForm.value.networkType, null)
        detailDialogVisible.value = true
    })

}

function closeDialog() {
    detailDialogVisible.value = false
    alarmForm.value = {}
}

const resolveChartData = (data) => {
    // 数组根据event_date字段是否相同进行重组,相同则将对应的county字段值放入children数组中
    return data.reduce((acc, item) => { // 定义一个函数，用于处理 testJson 数据，将其转换为特定格式的数组
        const existingDate = acc.find((entry) => entry.date === item.event_date); // 在累加器数组中查找是否存在与当前项 event_date 相同的日期
        if (existingDate) { // 如果找到了相同日期的条目
            existingDate.children.push({ // 将当前项的 county 和 count_county_alarm 添加到该日期的 children 数组中
                county: item.county,
                value: item.count_county_alarm
            });
        } else {
            acc.push({ // 如果没有找到相同日期的条目，则创建一个新的日期条目
                date: item.event_date, // 设置日期
                children: [ // 初始化 children 数组，并将当前项的 county 和 count_county_alarm 添加进去
                    {
                        county: item.county,
                        value: item.count_county_alarm
                    }
                ]
            });
        }
        return acc; // 返回累加器数组，供下一次迭代使用
    }, []) // 初始累加器为一个空数组
}

function loadMaintenanceAlarmStatistics() {
    queryMaintenanceAlarmStatistics().then(res => {
        alarmStatisticsData.value = res.data
        // console.log('alarmStatisticsData', alarmStatisticsData.value)

        /* let chartData = resolveChartData(testJson)
        console.log('chartData', chartData)

        initCountyBar(chartData) */

        initCountyBar()
    })
}

function initCountyBar() {
    var myChart = echarts.init(document.getElementById("echart"))
    var option;

    let countyList = [], realTimeAlarmTotal = [], realTimeAlarmRatio = [];
    if (alarmStatisticsData.value) {
        for (var i = 0; i < alarmStatisticsData.value.length; i++) {
            countyList.push(alarmStatisticsData.value[i].county)
            realTimeAlarmTotal.push(alarmStatisticsData.value[i].realTimeAlarmNum)
            realTimeAlarmRatio.push(alarmStatisticsData.value[i].realTimeAlarmRatio)
        }
    }

    option = {
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            }
        },
        legend: {
            data: ['未恢复告警总量', '未恢复量规模占比']
        },
        toolbox: {
            show: true,
            orient: 'vertical',
            left: 'right',
            top: 'center',
        },
        xAxis: [
            {
                type: 'category',
                name: '区县',
                data: countyList
            }
        ],
        yAxis: [
            {
                type: 'value',
                name: '未恢复告警总量',
                position: 'left',
                alignTicks: true,
                axisLine: {
                    show: true,
                    lineStyle: {
                        //color: colors[2]
                    }
                }
            },
            {
                type: 'value',
                name: '未恢复量规模占比',
                position: 'right',
                alignTicks: true,
                axisLine: {
                    show: true,
                    lineStyle: {
                        //color: colors[2]
                    }
                }
            }
        ],
        series: [
            {
                name: '未恢复告警总量',
                type: 'bar',
                barGap: 0,
                emphasis: {
                    focus: 'series'
                },
                yAxisIndex: 0,
                data: realTimeAlarmTotal
            },
            {
                name: '未恢复量规模占比',
                type: 'bar',
                emphasis: {
                    focus: 'series'
                },
                yAxisIndex: 1,
                data: realTimeAlarmRatio
            }
        ]
    };

    option && myChart.setOption(option);
}

/* const initCountyBar = (chartData) => {
    console.log('initCountyBar', chartData)
    var myChart = echarts.init(document.getElementById("echart"))
    var option;

    option = {
        tooltip: {
            trigger: 'axis'
        },
        legend: {
            data: chartData[0].children.map(item => item.county),
            bottom: 0
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '8%',
            containLabel: true
        },
        toolbox: {
            feature: {
                saveAsImage: {}
            }
        },
        xAxis: {
            // type: 'category',
            // boundaryGap: false,
            type: 'category',
            axisTick: {
                show: false,  // 隐藏刻度线
            },
            axisLine: {
                lineStyle: {
                    color: 'rgba(255, 255, 255, .6)', // 设置横坐标线颜色
                }
            },
            axisLabel: {
                interval: 0, // 横轴信息全部显示
                rotate: 30,
                color: '#333',
                fontSize: 10.5,
                align: 'center',
                margin: 20
            },
            // data: dateArr,
            data: chartData.map(item => item.date),
        },
        yAxis: {
            type: 'value'
        },
        series: chartData[0].children.map((child, index) => {
            return {
                name: child.county,
                type: 'line',
                stack: 'Total',
                data: chartData.map(item => item.children[index]?.value || 0)
            };
        }),
    };

    option && myChart.setOption(option);
} */

function filterChange(filters) {
    nowStatus.value = filters.serious[0];
    listRealTimeAlarmData();
}

/* function exportData1() {
    const param = {}
    param.pageSize = pageSize.value;
    param.pageNum = currentPage.value;
    param.county = queryParams.value.county
    param.neName = queryParams.value.neName
    param.alarmTitle = queryParams.value.alarmTitle
    param.networkType = queryParams.value.networkType
    param.serious = nowStatus.value;
    proxy.download("/maintenance/exportRealAlarmList", {
        ...param
    }, `无线维护告警_${new Date().getTime()}.xlsx`);
} */

function exportData() {
    const param = {}
    param.pageSize = pageSize.value;
    param.pageNum = currentPage.value;
    param.county = queryParams.value.county
    param.neName = queryParams.value.neName
    param.alarmTitle = queryParams.value.alarmTitle
    param.networkType = queryParams.value.networkType
    param.serious = nowStatus.value;
    //首先判断金库模式开关是否开启
    if (securityFlagConfig.configValue == "true") {
        refExportDialog.value.show(param)
    } else {
        //未开启
        proxy.download("/maintenance/exportRealAlarmList", {
            ...param
        }, `无线维护告警_${new Date().getTime()}.xlsx`);
    }
}

function directExportData() {
    const param = {}
    param.county = queryParams.value.county
    param.markFlag = queryParams.value.markFlag
    param.exitFlag = queryParams.value.exitFlag
    param.clearFlag = queryParams.value.clearFlag
    //创建时间
    if (queryParams.value.createStartEnd && queryParams.value.createStartEnd.length > 0) {
        param.createStart = queryParams.value.createStartEnd[0].toLocaleDateString()
        param.createEnd = queryParams.value.createStartEnd[1].toLocaleDateString()
    }
    proxy.download("/maintenance/exportRealAlarmDirectList", {
        ...param
    }, `无线维护告警(剔除敏感数据)_${new Date().getTime()}.xlsx`);
}

function submitApprove() {
    //提交审核



}

function unsetQueryForm() {
    queryParams.value = {
        county: '',
        neName: '',
        alarmTitle: '',
        networkType: '',
        serious: ''
    }
}

function showConfigDialog() {
    listAlarmExclude()
    configDialogVisible.value = true
}

function listAlarmExclude() {
    queryAlarmExcludeList().then(res => {
        alarmExcludeData.value = res.data
    })
}

function showAddAlarmExclude() {
    addDialogVisible.value = true
}

function closeAddDialog() {
    addForm.value = {}
    addDialogVisible.value = false
}

function doAddAlarmExclude() {
    let form = {
        alarmTopic: addForm.value.alarmTopic,
    }
    addAlarmExclude(form).then(res => {
        ElMessage.success('操作成功！')
        addDialogVisible.value = false
        listAlarmExclude()
    })
}

function handleDelete(row) {
    let param = {
        id: row.id
    }
    proxy.$modal.confirm('是否确认删除ID为"' + row.id + '"的数据项？').then(function () {
        return deleteAlarmExclude(param);
    }).then(() => {
        listAlarmExclude()
        ElMessage.success('操作成功！')
    }).catch(() => { });
}

listRealTimeAlarmData()
loadMaintenanceAlarmStatistics()


</script>